package com.xupt.dangjian.util;

import javax.activation.MimetypesFileTypeMap;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.github.tobato.fastdfs.service.TrackerClient;

import com.xupt.dangjian.entity.Article;
import com.xupt.dangjian.entity.File;
import com.xupt.dangjian.exception.MyException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class FileUtil {

    @Autowired
    public  static FastFileStorageClient fastFileStorageClient;
    @Autowired
    public  static TrackerClient trackerClient;

    @Value("${nginx}")
    public static String yuming;

    @Autowired
    public FileUtil(FastFileStorageClient fastFileStorageClient,TrackerClient trackerClient){
        this.fastFileStorageClient=fastFileStorageClient;
        this.trackerClient=trackerClient;
    }

    @Value("${nginx}")
    public void setYuming(String yuming){
        this.yuming=yuming;
    }

    public static File fileUpLoad(MultipartFile multipartFile) throws Exception {
        InputStream inputStream = multipartFile.getInputStream();
        System.out.println(fastFileStorageClient);
        StorePath storePath = fastFileStorageClient.uploadFile( inputStream, multipartFile.getSize(), FilenameUtils.getExtension( multipartFile.getOriginalFilename() ), null );
        inputStream.close();
        File file = new File();
        file.setName( multipartFile.getOriginalFilename() );
        file.setSize( (int) multipartFile.getSize() );
        file.setType( multipartFile.getContentType() );
        file.setUrl( yuming + "/" + storePath.getFullPath() );
        file.setCreatedTime( new Date() );
        System.out.println( file );
        return file;

    }

    public static File stringUpLoad(Article article) throws Exception {
        String s = article.getContent();
        InputStream inputStream = getStringStream( s );
        int size = s.getBytes( "GBK" ).length;
        StorePath storePath = fastFileStorageClient.uploadFile( inputStream, size, "txt", null );


        inputStream.close();
        File file = new File();
        file.setName( article.getTitle() + ".txt" );
        file.setSize( size );
        file.setType( "text/html" );

        file.setUrl( yuming + "/" + storePath.getFullPath() );
        file.setCreatedTime( new Date() );

        return file;

    }

    public File localFileUpLoad(String path) throws Exception {
        java.io.File localFile = new java.io.File( path );
        InputStream inputStream = new FileInputStream( localFile );
        StorePath storePath = fastFileStorageClient.uploadFile( inputStream, localFile.length(), FilenameUtils.getExtension( localFile.getName() ), null );
        inputStream.close();
        File file = new File();
        file.setName( localFile.getName() );
        file.setSize( (int) localFile.length() );
        file.setType( new MimetypesFileTypeMap().getContentType( localFile ) );
        file.setUrl( storePath.getFullPath() );
        return file;
    }

    public static List<File> filesUpLoad(MultipartFile[] multipartFiles) throws Exception {
        List<File> fileList = new ArrayList<File>();
        for (MultipartFile multipartFile : multipartFiles) {
            File file = fileUpLoad( multipartFile );
            fileList.add( file );
        }
        return fileList;
    }

    public static void download(OutputStream out, String fullPath) throws Exception {
        int index = fullPath.indexOf( '/' );
        fullPath = fullPath.substring( index + 1 );
        index = fullPath.indexOf( '/' );
        String group = fullPath.substring( 0, index );
        String path = fullPath.substring( index + 1 );
        InputStream inputStream = fastFileStorageClient.downloadFile( group, path, new DownloadInputStream() );
        byte buffer[] = new byte[1024];
        int len = 0;
        try { //循环将输入流中的内容读取到缓冲区当中
            while ((len = inputStream.read( buffer )) > 0) {
                //输出缓冲区的内容到浏览器，实现文件下载
                out.write( buffer, 0, len );
            }
        } catch (Exception e) {
            throw new MyException( "文件下载异常" );
        } finally {
            inputStream.close();
            out.close();
        }
    }


    public static String fileToString(String fullPath) throws Exception {
        int index = fullPath.indexOf( '/' );
        fullPath = fullPath.substring( index + 1 );
        index = fullPath.indexOf( '/' );
        String group = fullPath.substring( 0, index );
        String path = fullPath.substring( index + 1 );
        InputStream inputStream = fastFileStorageClient.downloadFile( group, path, new DownloadInputStream() );
        StringBuffer buffer = new StringBuffer();
        BufferedReader bf = new BufferedReader( new InputStreamReader( inputStream, "GBK" ) );
        byte byteBuffer[] = new byte[1024];

        int len = 0;
        //循环将输入流中的内容读取到缓冲区当中
        while ((len = inputStream.read( byteBuffer )) > 0) {
            //输出缓冲区的内容到浏览器，实现文件下载
            buffer.append( new String( byteBuffer, 0, len, "GBK" ) );
        }


        String content = buffer.toString();


        return content;

    }


    public static void delete(String fullPath) throws Exception {
        int index=0;

        index = fullPath.indexOf( '/' );
        fullPath = fullPath.substring( index + 1 );
        index = fullPath.indexOf( '/' );
        String group = fullPath.substring( 0, index );
        String path = fullPath.substring( index + 1 );
        System.out.println(group);
        System.out.println(path);
        fastFileStorageClient.deleteFile( group, path );
    }

    public static String matchStringFromFile(String fullPath, String regex) throws Exception {
        int index = fullPath.indexOf( '/' );
        fullPath = fullPath.substring( index + 1 );
        index = fullPath.indexOf( '/' );
        String group = fullPath.substring( 0, index );
        String path = fullPath.substring( index + 1 );
        InputStream inputStream = fastFileStorageClient.downloadFile( group, path, new DownloadInputStream() );
        StringBuffer buffer = new StringBuffer();
        BufferedReader bf = new BufferedReader( new InputStreamReader( inputStream ) );
        String s = null;
        while ((s = bf.readLine()) != null) {//使用readLine方法，一次读一行
            buffer.append( s.trim() );
        }

        String html = buffer.toString();
        Pattern pattern = Pattern.compile( regex );
        Matcher matcher = pattern.matcher( html );
        String matcherString = null;
        if (matcher.find()) {
            matcherString = matcher.group();

        }
        return matcherString.substring( 1, matcherString.length() - 1 );
    }


    public static InputStream getStringStream(String sInputString) {
        if (sInputString != null && !sInputString.trim().equals( "" )) {
            try {
                ByteArrayInputStream tInputStringStream = new ByteArrayInputStream( sInputString.getBytes( "GBK" ) );
                return tInputStringStream;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }


}


class DownloadInputStream implements DownloadCallback<InputStream> {
    @Override
    public InputStream recv(InputStream inputStream) throws IOException {
        return inputStream;
    }
}
